package com.platform.comm.enums.converters;

import com.platform.comm.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Description: Spring ConverterFactory
 *
 * @author libin Created on 2019/7/17
 **/
public class ConverterEnumFactory implements ConverterFactory<String, BaseEnum<?>> {

    private static final String NULL_KEY = "NULL PARAM";
    private static final Map<String, Converter<String, BaseEnum<?>>> CONVERT_MAP = new HashMap<>();
    @SuppressWarnings("unchecked")
    @Override
    public <T extends BaseEnum<?>> Converter<String, T> getConverter(Class<T> targetType) {

        String name = targetType.getName();
        if (!CONVERT_MAP.containsKey(name)) {
            CONVERT_MAP.put(name, Stream.of(targetType.getEnumConstants()).collect(Collectors.toMap(this::toString, e -> e))::get);
        }
        return (Converter<String, T>) CONVERT_MAP.get(name);
    }

    private String toString(BaseEnum<?> object) {
        Serializable param = object.getValue();
        return param != null ? param.toString(): NULL_KEY;
    }
}
